<?php
/**
 * Created by PhpStorm.
 * User: allen_ios
 * Date: 16/11/24
 * Time: 上午11:53
 */

namespace Task\App\Doorbjhq;
use Task\Core\Base;
use Task\Core\Http;
use \Task\Core\WechatApi;


class SyncDoorbjhqExceptList extends Base
{
    protected $mysql;
    protected $doormysql;

    public function __construct()
    {
        parent::__construct();
        $this->mysql = $this->selectDB('mysql');
        $this->doormysql = $this->selectDB('doorctrl_bjhq');
    }


    public function getExceptList()
    {
        $accountId = 2;
        //通过accountId去查applyId
        $ac_sql = 'select apply_id from gc_door_apply where account_id = '.$accountId;
        $resIdArr = $this->mysql->query($ac_sql)->fetch(\PDO::FETCH_ASSOC);
        $applyId = $resIdArr['apply_id'];

        //通过今天的日期去查不同的表，当是1号的时候，去查上个月的表，条件是create_time是今天的数据
        $day = date("d", time());
        $year = date("Y", time());
        $month = date("m", time());
        //发送的消息模板后点击跳转的页面url
        $url = config("new_wap_url").'/DoorctrlBjhq/Index/abnormal/applyId/'.$applyId.'/date/'.date('Y-m-d',strtotime('-1 day'));

        if ($day == 1) {
            //1月1号的时候，去查去年12月的表
            if($month - 1 == 0){
                $showName = 'gc_door_personal_statistic_' . $year - 1 . '_12';
            }else{
                $showName = 'gc_door_personal_statistic_' . $year . '_' . $month - 1;
            }
        } else {
            //不是一号，所以，不用判断年份
            $showName = 'gc_door_personal_statistic_' . $year . '_' . $month;
        }
        //今天的时间戳区间
        $start = strtotime(date("Y-m-d", time()));
        $end = $start + 24 * 3600 - 1;

        $sql = 'select * from ' . $showName . ' where cut_off = 0 and status = 4 and create_time >= ' . $start . ' and create_time <= ' . $end . ' and apply_id = ' . $applyId;
//        $sql = 'select class_id from ' . $showName . ' where cut_off = 0 and status = 4 and create_time >= 1501744505 and create_time <= 1501744508 and apply_id = ' . $applyId;

        $result = $this->doormysql->query($sql)->fetchAll(\PDO::FETCH_ASSOC);

        foreach ($result as $k => $v) {
            $sqls = 'select user_id from gc_door_auth_manage where manage_id in (select manage_id from gc_door_auth where class_id = '.$v['class_id'].' and cut_off = 0) and cut_off = 0 and account_id = '.$accountId;

            $userResult = $this->mysql->query($sqls)->fetchAll(\PDO::FETCH_ASSOC);
//            cdump($userResult) ;cdump($sqls);
            foreach ($userResult as $kk=>$vv) {
                $a= $this->sendMsg($vv['user_id'],$accountId,$url);
//                cdump($a);
//                $a= $this->msgTest($v['user_id'],$accountId);
            }
//            $this->msgTest();
//
        }

//        return $userResult;
    }

/**
 * 查找wechatid sql
 */
    public function sendMsg($user_id,$accountId,$url){

        $wechatSql = "select * from gc_wechat where account_id=".$accountId." limit 1";
        $wechats = $this->mysql->query($wechatSql)->fetch(\PDO::FETCH_ASSOC);

        $wechat = new WechatApi($wechats[0],$accountId);

        //推送给管理员
        $wechatuserSql = "select openid,subscribe,wechat_id from gc_wechat_user where user_id=".$user_id." limit 1";
        $wechatUserInfo = $this->mysql->query($wechatuserSql)->fetch(\PDO::FETCH_ASSOC);
        

        if ($accountId == 60) {
            $template_id = '_hHj0eU1ZQ7yorFomzpQvFV21NxQj8S_bqolOO9sbBk';
        }else if($accountId == 2){
            $template_id = 'SCWM-1-rlyk47b9nNXRZ1VgYY1EkbwNXTKLu8YAKJRs';
        }else{
            $template_id = '';
        }

        if($accountId == 60){
            $info = array(
                'first' => array("value" => '考勤结果通知！','color' => '#173177'),
                'keyword1' => array("value" => date('Y-m-d',time()),"color" => "#173177" ),
                'keyword2' => array("value" => 11111,"color" => "#173177"),
                'keyword3' => array("value" => date("Y-m-d H:i:s"),"color" => "#173177"),
                'remark' => array("value" => "点击查看详情！","color" => "#173177"),
            );
        }else if($accountId == 2){
            $info = array(
                'first' => array("value" => '考勤结果通知！','color' => '#173177'),
                'keyword1' => array("value" => date('Y-m-d',time())),
                'keyword2' => array("value" => '您有异常名单通知,请查看!',"color" => "#173177"),
                'remark' => array("value" => "点击查看详情！","color" => "#173177"),
            );
        }else{
            $info = array(
                'first' => array("value" => '考勤结果通知！','color' => '#173177'),
                'keyword1' => array("value" => date('Y-m-d',time())),
                'keyword2' => array("value" => 111111,"color" => "#173177"),
                'remark' => array("value" => "点击查看详情！","color" => "#173177"),
            );
        }
//        return $wechats[0]['appid'].'|'.$wechats[0]['appsecret'].'|'.$wechatUserInfo[0]['openid'].'|'.$template_id.'|'.$info.'|'.$url;
        $res = $wechat->messageTpl($wechats[0]['appid'], $wechats[0]['appsecret'], $wechatUserInfo[0]['openid'], $template_id, $info, $url);
//        return $res;
    }

    public function msgTest($user_id,$accountId) {

        //推送给管理员
        $wechatuserSql = "select openid,subscribe,wechat_id from gc_wechat_user where user_id=".$user_id." limit 1";
        $wechatUserInfo = $this->mysql->query($wechatuserSql)->fetch(\PDO::FETCH_ASSOC);

        $openid = $wechatUserInfo['openid'];
        $accessToken = 'sqHgmvPotp9Cz82htdOKPviLQeuXJzn6SjtOEzNhNb9SjNti4WzfVRyjQLkSLBmQ_T7mo1qWTPXe6qFrqALetK7pgYfjfpZEZ4WB8aX8o8mOYpqKIeGiWf0g8WkDr-cKFZKgADASMX';
        $templateId = '_hHj0eU1ZQ7yorFomzpQvFV21NxQj8S_bqolOO9sbBk';
        $messageUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;
        $data = array(
            'touser' => $openid,
            'template_id' => $templateId,
            'url' => 'http://hqwx.zjgsu.edu.cn/base/center/center/account_id/17',
            'topcolor' => '#FF0000',
            'data' => array(
                'first' => array("value" => '考勤结果通知！','color' => '#173177'),
                'keyword1' => array("value" => date('Y-m-d',time()),"color" => "#173177" ),
                'keyword2' => array("value" => 11111,"color" => "#173177"),
                'keyword3' => array("value" => date("Y-m-d H:i:s"),"color" => "#173177"),
                'remark' => array("value" => "点击查看详情！","color" => "#173177"),
            ),
        );

//        $result = Http::curlPost($messageUrl,json_encode($data));
        $result = $this->curl_post_info($messageUrl, json_encode($data));

        echo '<br><br>send result:---'.var_export($result,true).'<br>';
    }

    /**
     * Curl向特定url post数据
     */
    public function curl_post_info($url, $data){
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = json_decode(curl_exec($ch),true);
        if (curl_errno($ch)) {
            return false;
        }else{
            return $tmpInfo;
        }
        curl_close($ch);
    }
}